package com.benyi.util.rest;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class Session {
	
	private static Logger log=LoggerFactory.getLogger(Session.class);
	private static HashMap<String,String> verCode=new HashMap<String,String>();
	private static HashMap<String,Long> verTime=new HashMap<String,Long>();
	
	public static void saveVerifyCode(String code){
		if(RequestContextHolder.getRequestAttributes()==null){
			return;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession ss=request.getSession();		
		ss.setAttribute("vcode",code);
	}
	 
	public static void saveVerifyCode(String key,String code){
		verCode.put(key, code);
		verTime.put(key, System.currentTimeMillis());
	}
	
	public static boolean verifyCode(String dir,String fileName,String code){
		Object []ks=verTime.keySet().toArray();
		long t=System.currentTimeMillis();
		for(int i=0;i<ks.length;i++) {
			if( (t-verTime.get(ks[i]).longValue())/1000 > 600 ) { //10 分钟不使用
				verTime.remove(ks[i]);
				verCode.remove(ks[i]);
				
				File f=new File(dir,ks[i]+".jpeg");
				if(f.exists()) {
					f.delete(); //用过后删除
				} 
			}
		}
		
		File f=new File(dir,fileName);
		if(f.exists()) {
			f.delete(); //用过后删除
		} 
		
		String key=fileName;
		int index=fileName.indexOf(".");
		if(index>0) {
			key=fileName.substring(0,index);
		}
		
		String v=verCode.get(key);
		if(v==null) {
			return false;
		}
		if(v.equalsIgnoreCase(code)) {
			verTime.remove(key);
			return true;
		}
		return false;
	}
	
	public static boolean verifyCode(String code){
		if(RequestContextHolder.getRequestAttributes()==null){
			return true;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession ss=request.getSession();		
		String v=(String)ss.getAttribute("vcode");
		ss.removeAttribute("vcode");
		if(v!=null && v.equalsIgnoreCase(code)){
			return true;
		}
		return false; 
	}
	
	public static String getAppPath(){ 
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String dir = request.getServletContext().getRealPath("/");
		return dir; 
	} 
	
	public static String getValue(String name){
		if(RequestContextHolder.getRequestAttributes()==null){
			return null;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession ss=request.getSession();		
		String v=(String)ss.getAttribute(name);
		ss.removeAttribute(name);
		return v;
	}
	
	public static boolean setValue(String name,String value){
		if(value==null || name==null) {
			return false;
		}
		if(RequestContextHolder.getRequestAttributes()==null){
			return false;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpSession ss=request.getSession();		
		ss.setAttribute(name,value);   
		return true;
	}
	
	public static String getClientIp(){
		if(RequestContextHolder.getRequestAttributes()==null){
			return null;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String ips=request.getHeader("x-forwarded-for");
		String ip=null;
		if(ips!=null) {
			String []ps=ips.split(",");
			for(int i=0;i<ps.length;i++) {
				if(isValidIp(ps[i])) {
					ip=ps[i];
					break;
				}
			}
		}
		if(ip==null) {
			ip=request.getRemoteAddr();
		} 
		return ip;
	}
	
	private static boolean isValidIp(String ip) {
		if(ip==null || ip.length()==0) {
			return false;
		}
		int from=0;
		int index=ip.indexOf(".");
		int n=0; 
		char c;
		while(index>0) {
			n++;
			if(index-from>3) { //不能超过 3 个数字 
				return false;
			}
			boolean ok=false;
			while(from<index) {
				c=ip.charAt(from);
				if( c>'9' || c < '0' ) {
					ok=false;
					break;
				}
				ok=true;
				from++;
			}
			if(ok==false) {
				return false;
			}
			from=index+1;
			index=ip.indexOf(".",index+1);
		} 
		if(n!=3) {
			return false;
		}
		String t=ip.substring(from);
		if(t.length()>3 || t.length()<1) {
			return false;
		}
		from=0;
		while(from<t.length()) {
			c=t.charAt(from);
			if( c>'9' || c < '0' ) {
				return false;
			}
			from++;
		}
		return true;
	}
	
	public static String getRequestParameter(String name){
		if(RequestContextHolder.getRequestAttributes()==null){
			return null;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String value=request.getParameter(name);
		return value;
	}

	public static String getRequestHeader(String name){
		if(RequestContextHolder.getRequestAttributes()==null){
			return null;
		}
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String value=request.getHeader(name);
		return value;
	}
	
	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	public static HttpServletResponse getResponse() {
		HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		return res;
	}
	
	public static void writeImage(String file,byte []image) throws IOException{
		
		HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		OutputStream out=res.getOutputStream();
		int index=file.lastIndexOf(".");
		String type="image/"+file.substring(index+1); 
		res.setHeader("Content-Type", type); 
		out.write(image);
		out.flush();
	}
	
	
	public static void writeFile(String file,byte []content) throws IOException{
		
		HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		OutputStream out=res.getOutputStream(); 
		res.setContentType("multipart/form-data");    
        res.setHeader("Content-Disposition", "attachment;fileName="+file);  
		out.write(content);
		out.flush();
	}
	
	
	public static void writeHtml(String msg) throws IOException{
		
		HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		OutputStream out=res.getOutputStream(); 
		res.setHeader("Content-Type", "text/html;charset=UTF-8"); 
		out.write(msg.getBytes("utf-8"));
		out.flush();
	}
	
	public static void download(File file,byte []content) throws IOException{
		
		HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		OutputStream out=res.getOutputStream(); 
		String name=file.getName();
		res.setContentType("application/octet-stream;charset=ISO8859-1");  
        res.setHeader("Content-Disposition","attachment;filename=\"" + name + "\"");  
        res.setHeader("Content-Length", String.valueOf(content.length)); 
        out.write(content);
		out.flush();
	} 
	
	public static byte[] readFile(File f){
		try {
			ByteArrayOutputStream bo=new ByteArrayOutputStream();
			BufferedInputStream bi=new BufferedInputStream(new FileInputStream(f));
			try {
				int i=bi.read();
				while(i!=-1){
					bo.write(i);
					i=bi.read();
				}
				bi.close();
				bo.close(); 
				return bo.toByteArray(); 
			} catch (IOException e) {
				log.error("读取文件失败{}",f.getAbsolutePath(),e);
			} 
		} catch (FileNotFoundException e) { 
			log.error("文件不存在",e);
		}
		return null;
	}
	
	public static void main(String []args) {
		String ip="231.01.101.101";
		System.out.println(isValidIp(ip));
	}
}
